﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Windows.Forms.Design;

namespace Fonlow.BetterRobocopyGui
{
    public partial class RashFlagsUc : UserControl
    {
        public RashFlagsUc()
        {
            InitializeComponent();
        }

        public RashFlagsUc(Rashcneto flags) : this()
        {
            Flags = flags;
        }

        public Rashcneto Flags
        {
            get
            {
                return (Rashcneto)GetFlags(checkedListBox);
            }

            set
            {
                LoadFlagsToCheckedList((int)value, checkedListBox);
            }
        }

        private static void LoadFlagsToCheckedList(int flags, CheckedListBox checkedListBox)
        {
            int flagTotal = checkedListBox.Items.Count;

            for (int i = 0; i < flagTotal; i++)
            {
                int flagMark = 1 << i;
                checkedListBox.SetItemChecked(i, (flagMark & flags) != 0);
            }
        }

        private static int GetFlags(CheckedListBox checkedListBox)
        {
            int flagTotal = checkedListBox.Items.Count;
            int flags = 0;
            for (int i = 0; i < flagTotal; i++)
            {
                int flagMark = 1 << i;
                if (checkedListBox.GetItemChecked(i))
                {
                    flags |= flagMark;
                }
            }
            return flags;
        }
    }

    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    public class RashFlagsEditor : UITypeEditor
    {
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (value.GetType() != typeof(Rashcneto))
                return value;

            // Uses the IWindowsFormsEditorService to display a 
            // drop-down UI in the Properties window.
            IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
            if (edSvc != null)
            {
                RashFlagsUc flagsUc = new RashFlagsUc((Rashcneto)value);
                edSvc.DropDownControl(flagsUc);
                return flagsUc.Flags;
            }
            return value;

        }

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.DropDown;
        }

    }
}
